package pth.authentication.service;

import lombok.RequiredArgsConstructor;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import pth.authentication.context.RbacContext;
import vin.pth.base.exception.authentication.AuthenticationException;
import vin.pth.base.pojo.GrantedAuthority;

/**
 * 默认的RbacService.
 *
 * @author cocoon
 */
@RequiredArgsConstructor
public class DefaultRbacServiceServiceImpl implements RbacService {

  private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

  @Override
  public void checkPermission(RbacContext context)
      throws AuthenticationException {

    for (GrantedAuthority authority : context.getUserDetails().getAuthority()) {
      if (ANT_PATH_MATCHER.match(authority.getUri(), context.getPath())) {
        if ("*".equals(authority.getMethod()) || authority.getMethod()
            .equalsIgnoreCase(context.getMethod())) {
          return;
        }
      }
    }
    if (StringUtils.hasText(context.getToken())) {
      throw new AuthenticationException("您没有权限!");
    }
    throw new AuthenticationException("请登陆后重试!");

  }
}
